#!/usr/bin/python
"""
language.py

Glue a parser and lexer together.  Construct objects from module naming
conventions.

"""

# Public functions obey PEP 8 naming.
__all__ = [
    'build_lexer', 'build_parser', 'build_language',
    'Language',
    ]

import lexer
import tpe_compile
import util


def build_lexer(m):
  """
  Args:
    m: module name or string
  """
  d = util.get_value(m, dict, 'LEXER')
  return lexer.Lexer(d)


def build_parser(m):
  """
  Args:
    m: module name or string
  """
  actions = util.get_actions(m)
  rules = util.get_value(m, basestring, 'RULES')
  p = tpe_compile.Parser(rules, actions)
  return p


def build_language(m):
  """
  Args:
    m: module name or string
  """
  l = build_lexer(m)
  p = build_parser(m)
  return Language(l, p)


class Language(object):

  def __init__(self, lexer, parser):
    self.lexer = lexer
    self.parser = parser

  def parse(self, s, start='Start'):
    """
    Args:
      s: string to parse

    Returns:
      Result of the parser.

    Raises:
      lexer.Error ?
      tpe_compile.Error ?
    """
    # TODO: any 
    tokens = list(self.lexer.run(s))
    # TODO: reverse order of args
    return self.parser.parse(tokens, start=start)

